package com.smedi.ismedi.personnel.core.port.adapter.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.smedi.ismedi.personnel.core.port.adapter.service.FdfsClientService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 将注解更新为 Component, 防止日志打印 byte[] 流
 *
 * @Author: xulinjun
 * @Date: 2021-6-9 10:46
 */
@Slf4j
@Component
@AllArgsConstructor
public class FdfsClientServiceImpl implements FdfsClientService {
    private final FastFileStorageClient storageClient;

    @Override
    public StorePath uploadFileStream(InputStream stream, String fileName) throws Exception {
        return storageClient.uploadFile(stream, stream.available(), FilenameUtils.getExtension(fileName), null);
    }

    @Override
    public StorePath uploadFile(File file) throws Exception {
        InputStream stream = new FileInputStream(file);
        return storageClient.uploadFile(stream, stream.available(), FilenameUtils.getExtension(file.getName()), null);
    }

    @Override
    public byte[] downloadFile(HttpServletResponse response, String group, String path, String fileName) {
        DownloadByteArray callback = new DownloadByteArray();
        return storageClient.downloadFile(group, path, callback);
    }

    @Override
    public void deleteFile(String group, String path) throws FdfsUnsupportStorePathException {
        storageClient.deleteFile(group, path);
    }
}
